﻿// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
// for details on configuring this project to bundle and minify static web assets.

// Write your JavaScript code.
var socket;
var wsPlayer;
var scheme = document.location.protocol === "https:" ? "wss" : "ws";
var port = document.location.port ? (":" + document.location.port) : "";
var img = document.getElementById('img');

var hubUrl = document.location.pathname + 'cnnctn';

var hubconnection = new signalR.HubConnectionBuilder()
    .withUrl(hubUrl, signalR.HttpTransportType.WebSockets)
    .configureLogging(signalR.LogLevel.None).build();
var subject = new signalR.Subject();
var callinguser = null;
var acceptinguser = "";
$(document).ready(function () {
    //server.value = scheme + "://" + document.location.hostname + port + "/ws";

    // Start the connection.
    var sigurl = "http://" + document.location.hostname + port + "/signal";

    var connection = new signalR.HubConnectionBuilder()
        .withUrl(sigurl)
        .build();

    connection.on('ImagePlay', function (message) {
        // Html encode display name and message.
        document.getElementById('img').src = '';
        var image = new Image();
        image.src = `data:image/jpeg;base64,${message}`;
        document.getElementById('img').src = image.src;
    });

    // Transport fallback functionality is now built into start.
    
    connection.start()
        .then(function () {
            console.log('connection started:' + sigurl);
            
        })
        .catch(error => {
            console.error(error.message);
        });
    

    $('input:radio[name="video"]').on('click', function () {
        var item = $(this).val();
        connection.invoke("SwitchVideo", "bob", Number(item));
        if (item == "2") {
            wsOpen();
        } else {
            wsClose();
        }
     })

    
});

function wsOpen() {
    var wsUrl = "ws://" + document.location.hostname + port + "/ws";
    var canvas = document.getElementById('video-canvas');
    wsPlayer = new JSMpeg.Player(wsUrl, { canvas: canvas, protocols: [], videoBufferSize: 1024*1024*8 });
}

function wsClose() {
    if (!wsPlayer) {
        return;
    }
    wsPlayer.stop()
    wsPlayer.destroy()
    wsPlayer = null
}

